const fs = require("fs");

// 自动读取router路由数据  window 文件夹分割符是 \
const readRouters = (router, dir) => {
    let files = fs.readdirSync(__dirname + "\\" + dir);
    let js_files = files.filter((file) => {
        return file.endsWith(".js");
    })
    // 处理每个文件
    for (let file_name of js_files) {
        let mapping = require(__dirname + "\\" + dir + "\\" + file_name);
        addRouter(router, mapping);
    }
}

// 渲染路由
function addRouter(router, mapping) {
    for (let path in mapping) {
        if (/^GET/i.test(path)) {
            router.get(path.split(" ")[1], mapping[path])
        } else if (/^POST/i.test(path)) {
            router.post(path.split(" ")[1], mapping[path])
        } else {
            // 无效的URL:
            console.log(`invalid URL: ${url}`);
        }
    }
}


module.exports = (dir) => {
    const router = require("koa-router")();
    dir = dir || "router";
    readRouters(router, dir);
    return router.routes();
}